<template>
  <el-form ref="ruleForm"
           :model="form"
           label-width="100px"
           label-position="left"
           size="small"
           style="position: relative"
           :rules="rules">
    <div class="goods-text">
      在下面表格里可直接添加物品信息，输入物品编码或物品名称可快速选择货物。
      <el-button type="primary"
                 :loading="loading"
                 plain
                 size="small"
                 @click="showAddGoods">
        选择已有物品
      </el-button>
      <select-more-goods v-if="goodsVisible"
                         :customer-id="form.customerId"
                         :goods-visible.sync="goodsVisible"
                         @selectMoreGoods="selectMoreGoods" />
    </div>
    <el-table ref="goodsTable"
              v-loading="loading"
              :data="form.goodsList"
              :header-cell-class-name="handlemyclass"
              max-height="468px">
      <el-table-column type="index"
                       align="center"
                       label="序号">
      </el-table-column>
      <template v-for="(column, index) in columns">
        <el-table-column :key="index"
                         :prop="column.prop"
                         :label="column.name"
                         :show-overflow-tooltip="false"
                         :render-header="renderHeader">
          <template slot-scope="scope">
            <div v-if="column.type === 'barcode'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        placeholder="请输入物料编码"
                        :readonly="!!scope.row.goodsId"
                        :maxlength="30"
                        @input="changeCode(scope.row[column.prop], scope.$index, 1)"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.prop === 'name'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        placeholder="请输入物品名称"
                        :class="[
                  {
                    repeatInput: scope.row.isRequire && !scope.row[column.prop]
                  }
                ]"
                        :readonly="!!scope.row.goodsId"
                        :maxlength="100"
                        @input="changeCode(scope.row[column.prop], scope.$index, 2)"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.prop === 'value'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        :class="[
                  {
                    repeatInput: scope.row.isRequire && !scope.row[column.prop]
                  }
                ]"
                        placeholder="请输入价值"
                        :readonly="!!scope.row.goodsId"
                        oninput="this.value=(this.value.match(/\d{0,7}(\.\d{0,2})?/)||[''])[0];"
                        @blur="blurAddList(scope.row, scope.$index)"
                        @input="totalAccount(scope.row, scope.$index)"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.type === 'spec'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        placeholder="请输入规格"
                        :class="[
                  {
                    repeatInput: scope.row.isRequire && !scope.row[column.prop]
                  }
                ]"
                        :maxlength="30"
                        :readonly="!!scope.row.goodsId"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.type === 'weight'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        placeholder="请输入重量(公斤)"
                        :class="[
                  {
                    repeatInput: scope.row.isRequire && !scope.row[column.prop]
                  }
                ]"
                        oninput="this.value=(this.value.match(/\d{0,5}(\.\d{0,4})?/)||[''])[0];"
                        :readonly="!!scope.row.goodsId"
                        @input="handleInput(scope.row, 'weight')"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.type === 'volume'">
              <el-input v-if="!scope.row.goodsId"
                        v-model="scope.row[column.prop]"
                        style="cursor: pointer"
                        placeholder="请输入体积(方)"
                        :class="[
                  {
                    repeatInput: scope.row.isRequire && !scope.row[column.prop]
                  }
                ]"
                        oninput="this.value=(this.value.match(/\d{0,3}(\.\d{0,6})?/)||[''])[0];"
                        :readonly="!!scope.row.goodsId"
                        @input="handleInput(scope.row, 'volume')"></el-input>
              <span v-else>{{ scope.row[column.prop] }}</span>
            </div>
            <div v-else-if="column.type === 'batchNo'">
              <el-input v-model.trim="scope.row[column.prop]"
                        :placeholder="scope.row.isRed ? '请修改批次' : ''"
                        :class="[{ repeatInput: scope.row.isRed }]"
                        maxlength="20"
                        @input="scope.row.goodsId ? repeatBatch() : ''"></el-input>
            </div>
            <el-input v-else-if="column.type === 'quantity'"
                      :id="scope.$index + 'wly_goods'"
                      :ref="'focus' + scope.$index"
                      v-model.number.trim="scope.row[column.prop]"
                      maxlength="8"
                      oninput="this.value=(this.value.match(/\d{0,8}(\d{0,0})?/)||[''])[0];"
                      placeholder="最多输入八位数"
                      @keyup.enter.native="keyEnter(scope.$index + 1, true)"
                      @blur="blurAddList(scope.row, scope.$index)"
                      @input="totalAccount(scope.row, scope.$index)"></el-input>
            <el-input v-else-if="column.type === 'remarks'"
                      v-model="scope.row[column.prop]"
                      maxlength="100"
                      style="cursor: pointer"
                      placeholder="请输入备注"></el-input>
            <div v-else-if="column.type === 'type'">
              <SelectNewType v-if="!scope.row.goodsId"
                             v-model="scope.row[column.prop]"
                             :class="{'repeatInput': scope.row.isRequire && !scope.row[column.prop]}"
                             :preset="{ size: 1000 }" />
              <span v-else>{{ scope.row.type }}</span>
            </div>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="操作"
                       width="240"
                       align="center">
        <template slot-scope="scope">
          <div class="operationSty">
            <el-button v-if="!(scope.$index === form.goodsList.length - 1)"
                       type="text"
                       onkeydown="if(event.keyCode==13){return false;}"
                       @click="deleteRow(scope.$index)">
              删除
            </el-button>
            <el-divider v-if="!(scope.$index === form.goodsList.length - 1)"
                        direction="vertical" />
            <el-button v-if="!scope.row.goodsId && Object.values(scope.row).length > 1"
                       type="text"
                       @click="addGoods(scope.row, scope.$index)">
              确定
            </el-button>
            <!-- <el-divider v-if="scope.row.goodsId"
                        direction="vertical" /> -->
            <el-button v-if="scope.row.goodsId"
                       type="text"
                       @click="resetRow(scope.$index)">
              清空
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <goods-total :total-list="form.totalList"
                 @totalDataAccount="totalDataAccount" />
    <select-goods v-if="showGoods"
                  :type="type"
                  :value="goodsValue"
                  :customer-id="formInfo.customerId"
                  :dialog-visible.sync="showGoods"
                  :filter="{}"
                  :style="`left:49px;top:${
        (form.goodsList.length - 1) * 49 + 136 > 500
          ? 518
          : (form.goodsList.length - 1) * 49 + 136
      }px`"
                  @selectRow="selectRow"
                  @addGoods="showAddGoods" />
    <order-complete-dialog v-if="visible"
                           :order-id="completeOrderId"
                           :visible.sync="visible"
                           :succese-tips="succeseTips"
                           @initActive="initActive" />
  </el-form>
</template>
<script>
import SelectGoods from "./components/SelectGoods.vue";
import OrderCompleteDialog from "./components/OrderCompleteDialog.vue";
import SelectMoreGoods from "./components/SelectMoreGoods.vue";
import SelectNewType from "./components/SelectNewType.vue";
import GoodsTotal from "./components/GoodsTotal.vue";
import { order, goods } from "@/api/index.js";
import baseMixin from "@components/mount/mixins/common";
import { Storage } from "@/libs/storage";

export default {
  name: "GoodsInfo",
  components: {
    SelectGoods,
    GoodsTotal,
    OrderCompleteDialog,
    SelectMoreGoods,
    SelectNewType
  },
  mixins: [baseMixin],
  props: {
    formInfo: {
      type: Object,
      default: () => { }
    },
    emptyForm: {
      type: Object,
      default: () => { }
    }
  },
  data () {
    return {
      btnLoading: false, //新增物品按钮loading
      loading: false,
      storage: new Storage("createForm", localStorage),
      completeOrderId: 0, //订单创建后id
      columns: [
        { name: "物料编码", prop: "barcode", type: "barcode" },
        { name: "*物品名称", prop: "name", type: "name" },
        { name: "*规格", prop: "spec", type: "spec" },
        { name: "*重量(公斤)", prop: "weight", type: "weight" },
        { name: "*体积(方)", prop: "volume", type: "volume" },
        { name: "*数量", prop: "quantity", type: "quantity" },
        { name: "*价值", prop: "value", type: "value" },
        { name: "*物品类型", prop: "type", type: "type" },
        { name: "批次", prop: "batchNo", type: "batchNo" },
        { name: "备注", prop: "remarks", type: "remarks" }
      ],
      rules: {},
      visible: false, //
      goodsVisible: false, // 新增物品弹窗
      active: 2,
      tableData: [{}],
      form: {},
      showGoods: false, //物品组件
      type: "", //物品查询名称
      goodsValue: "", //物品查询值
      filter: {},
      lastIndex: null, //数据位置
      userInfo: sessionStorage.getItem('userInfo')
    };
  },
  computed: {
    user () {
      return JSON.parse(this.userInfo)
    },
    userId () {
      return this.user?.userId
    }
  },
  watch: {
    emptyForm: {
      immediate: true,
      handler (val) {
        this.form = val;
      }
    }
  },
  created () {
    this.form = this.formInfo;
    if (this.form.goodsList.length === 0) {
      this.form.goodsList = [{ type: this.form.goodsType }];
    }
    this.addTotalList(true);
    this.form.totalList = [
      {
        goodsId: 0,
        name: "",
        barcode: "补差",
        batchNo: "",
        remarks: "",
        spec: "",
        quantity: 0,
        singleWeight: 0,
        singleVolume: 0,
        singleValue: 0,
        value: this.form.valueAddition,
        volume: this.form.volumeAddition,
        weight: this.form.weightAddition
      },
      {
        goodsId: 0,
        name: "",
        barcode: "合计",
        batchNo: "",
        remarks: "",
        spec: "",
        quantity: this.form.totalQuantity,
        singleWeight: 0,
        singleVolume: 0,
        singleValue: 0,
        value: (this.form.totalList[1].value && this.form?.calculateValue === this.form.totalList[1].value) || (!this.form.totalList[1].value && this.form.calculateValue) ? this.form.calculateValue : this.form.totalValue,
        volume: (this.form.totalList[1].volume && this.form?.calculateVolume === this.form.totalList[1].volume) || (!this.form.totalList[1].volume && this.form.calculateVolume) ? this.form.calculateVolume : this.form.totalVolume,
        weight: (this.form.totalList[1].weight && this.form?.calculateWeight === this.form.totalList[1].weight) || (!this.form.totalList[1].weight && this.form.calculateWeight) ? this.form.calculateWeight : this.form.totalWeight,
      }
    ];
    this.totalSignAccount()
  },
  methods: {
    // 表头样式
    handlemyclass ({ row, column, rowIndex, columnIndex }) {
      if ([2, 3, 4, 5, 6, 7, 8].includes(columnIndex)) return "cellSty";
    },
    renderHeader (h, { column, $index }) {
      if (['*重量(公斤)', '*体积(方)', '*价值'].includes(column.label)) {
        const labelArr = { 4: '重量', 5: '体积', 7: '价值' }
        let val = labelArr[$index];

        return [column.label,
        h(
          'el-tooltip',
          {
            props: {
              content: `单个物品${val}`,
              placement: 'top'
            }
          },
          [h('span', { class: { 'el-icon-question': true } })]
        )]
      } else {
        return column.label
      }
    },
    // 删除行
    deleteRow (index) {
      this.form.goodsList.splice(index, 1);
      this.totalAccount();
    },
    // 重选
    resetRow (index) {
      let obj = ({} = Object.assign(
        {},
        {
          //物品信息
          batchNo: "",
          value: null,
          remarks: "",
          name: "",
          barcode: "",
          quantity: null,
          spec: "",
          volume: null,
          weight: null,
          goodsId: null
        }
      ));
      this.$set(this.form.goodsList, index, obj);
      this.totalAccount();
    },
    showAddGoods () {
      this.goodsVisible = true;
    },
    // 物品名称和编码输入
    changeCode (val, index, num) {
      if (val.length > 1) {
        if (num === 1) {
          this.type = "barcode";
        } else {
          this.type = "name";
        }
        this.goodsValue = val;
        this.showGoods = true;
        this.lastIndex = index;
      } else {
        this.showGoods = false;
      }
    },
    // 重量、体积合计计算回显
    totalDataAccount (data) {
      this.form.volumeAddition = data[0].volume;
      this.form.weightAddition = data[0].weight;
      this.form.valueAddition = data[0].value;
      this.form.totalValue = data[1].value;
      this.form.totalVolume = data[1].volume;
      this.form.totalQuantity = data[1].quantity;
      this.form.totalWeight = data[1].weight;
    },

    totalSignAccount () {
      this.form.totalList[1].singleWeight = 0;
      this.form.totalList[1].singleVolume = 0;
      this.form.totalList[1].singleValue = 0;
      this.form.goodsList.forEach((ele, index) => {
        if (index < this.form.goodsList.length) {
          this.form.totalList[1].singleWeight +=
            (ele.weight || 0) * (ele.quantity || 0);
          this.form.totalList[1].singleVolume +=
            (ele.volume || 0) * (ele.quantity || 0);
          this.form.totalList[1].singleValue +=
            (ele.value || 0) * (ele.quantity || 0);
        }
      });
    },
    // 合计体积、重量
    totalAccount (row, index) {
      if (row && row.value === ".") {
        return (row.value = null);
      }
      this.form.totalList[1].weight = 0;
      this.form.totalList[1].volume = 0;
      this.form.totalList[1].value = 0;
      this.form.totalList[1].quantity = 0;
      this.totalSignAccount();
      this.form.totalValue = 0;
      this.form.goodsList.forEach((ele, index) => {
        if (index < this.form.goodsList.length) {
          this.form.totalList[1].weight = Number(
            parseFloat(
              (this.form.totalList[1].weight +=
                (ele.weight || 0) * (ele.quantity || 0))
            ).toFixed(2)
          );
          this.form.totalList[1].volume = Number(
            parseFloat(
              (this.form.totalList[1].volume +=
                (ele.volume || 0) * (ele.quantity || 0))
            ).toFixed(2)
          );
          this.form.totalList[1].value = Number(
            parseFloat(
              (this.form.totalList[1].value +=
                (ele.value || 0) * (ele.quantity || 0))
            ).toFixed(2)
          );
          this.form.totalList[1].quantity += ele.quantity || 0;
          this.form.totalValue += ele.value;
        }
      });

      this.form.totalList[0].value = 0;
      this.form.totalList[0].weight = 0;
      this.form.totalList[0].volume = 0;
      this.form.volumeAddition = 0;
      this.form.weightAddition = 0;
      this.form.totalValue = this.form.totalList[1].value;
      this.form.totalVolume = this.form.totalList[1].volume;
      this.form.totalWeight = this.form.totalList[1].weight;
    },
    // 选择物品数量获取焦点
    keyEnter (index, down) {
      console.log("======<down", index, down)
      if (down) {
        if (index < this.form.goodsList.length - 1) {
          document.getElementById(index + "wly_goods").focus();
        }
      } else {
        document.getElementById(index + "wly_goods").focus();
      }
    },
    // 选择多个物品
    selectMoreGoods (data) {
      let isAdd = false;
      for (let i in this.form.goodsList[this.form.goodsList.length - 1]) {
        if (
          this.form.goodsList[this.form.goodsList.length - 1][i] &&
          i !== "type" &&
          i !== "isRequire"
        ) {
          isAdd = true;
        }
      }
      this.form.goodsList.length = this.form.goodsList.length - (isAdd ? 0 : 1);
      data.forEach((item) => {
        item.weight = item.netWeight;
        this.form.goodsList.push(item);
      });
      this.addTotalList(true);
    },
    // 物品赋值
    goodsInfo (row, type) {
      let selectRow = {
        name: row.name,
        barcode: row.barcode,
        weight: row.netWeight,
        value: row.value,
        type: row.type
      };
      Object.assign(selectRow, row);
      this.$set(
        this.form.goodsList,
        type ? this.lastIndex : this.form.goodsList.length - 1,
        selectRow
      );
      this.keyEnter(this.form.goodsList.length - 1, false)
    },
    // 选择物品
    selectRow (row) {
      this.goodsInfo(row, 1);
      if (this.lastIndex + 1 === this.form.goodsList.length) {
        this.addTotalList(true);
      }
    },
    // 新增物品
    async addGoods (row, index) {
      this.showGoods = false;
      let postData = {
        name: row.name,
        spec: row.spec,
        netWeight: row.weight,
        volume: row.volume,
        value: row.value,
        goodsTypeId: row.goodsTypeId || row.type
      };
      for (let i in postData) {
        if (!postData[i] && postData[i] !== 0) {
          this.$message.error(`必填字段不能为空`);
          this.$set(this.form.goodsList[index], "isRequire", true);
          return;
        }
      }
      postData.customerId = this.form.customerId;
      postData.barcode = row.barcode;
      this.btnLoading = true;
      let { code, data } = await goods.insert(postData);

      this.btnLoading = false;
      if (code === 0) {
        this.$set(this.form.goodsList[index], "goodsId", data.goodsId);
        this.$set(this.form.goodsList[index], "type", data.type);
        this.addTotalList(true);
      } else {
        this.$message.error("已为您找到了相同的物品信息，请重新选择");
      }
    },
    // 表格input失去焦点事件
    blurAddList (row) {
      if (
        Object.values(this.form.goodsList[this.form.goodsList.length - 1])
          .length !== 0
      ) {
        if (
          row.name &&
          row.value &&
          row.spec &&
          row.volume &&
          row.quantity &&
          row.weight &&
          row.type
        ) {
          this.addTotalList();
        }
      }
    },
    handleInput (row, item) {
      if (item === "volume" && row.volume === ".") row.volume = null;
      if (item === "weight" && row.weight === ".") row.weight = null;
    },
    addTotalList (scrollFlag) {
      if (this.form.goodsList[this.form.goodsList.length - 1].name) {
        this.form.goodsList.push({ type: this.form.goodsType });
      }
      if (scrollFlag) {
        this.$nextTick(() => {
          this.$refs.goodsTable.bodyWrapper.scrollTop =
            this.$refs.goodsTable.bodyWrapper.scrollHeight;
        });
      }
    },
    // 创建
    save () {
      let lastData = this.form.goodsList[this.form.goodsList.length - 1];
      for (let i in lastData) {
        if (lastData[i] && i !== "type" && i !== "isRequire") {
          this.$message.error(`请先确认添加物品`);
          return;
        }
      }

      let goodsIds = this.form.goodsList.filter((item) => {
        return !item.goodsId;
      });
      if (goodsIds.length > 1) {
        this.$message.warning("请先确认添加物品");
        return;
      }
      let hasGoodsIds = this.form.goodsList.find((item) => {
        return item.goodsId;
      });
      if (!hasGoodsIds) {
        this.$message.warning("物品信息不能为空");
        return;
      }
      //数量为空的物品信息
      let arr = this.form.goodsList.find((item) => {
        return item.goodsId && !item.quantity;
      });

      if (arr) {
        this.$message.error("物品数量不能为空或0");
      } else {
        if (this.repeatBatch() === false) return;

        // 重量校验
        if (this.form.chargeMode == 1 && Number(this.form.totalWeight) <= 0) {
          if (this.form.transportMode === 1) {
            return this.$message.error("计费模式为重量，物品总重量不能为空或小于0");
          } else if (
            this.form.transportMode === 2 &&
            (this.form.onLoad === 1 || this.form.offLoad === 1)
          ) {
            return this.$message.error("计费模式为重量，物品总重量不能为空或小于0");
          }
        }
        // 体积校验
        if (this.form.chargeMode == 2 && Number(this.form.totalVolume) <= 0) {
          if (this.form.transportMode === 1) {
            return this.$message.error("计费模式为体积，物品总体积不能为空或小于0");
          } else if (
            this.form.transportMode === 2 &&
            (this.form.onLoad === 1 || this.form.offLoad === 1)
          ) {
            return this.$message.error("计费模式为体积，物品总体积不能为空或小于0");
          }
        }
        // 总价值校验
        if (Number(this.form.totalValue) > 9999999999) {
          this.$message.error("总价值不能超过10位整数，请重新调整物品数量");
          return;
        }
        // 运输模式为整车时
        if (this.form.transportMode === 2) {
          if (this.form.vehicleMode.vehicleLength === "其他") {
            this.form.vehicleMode.vehicleLength = 999;
          }
          if (
            this.form.totalWeight >
            Number(this.form.vehicleMode.vehicleWeight) *
            1000 *
            this.form.vehicleMode.vehicleCount ||
            this.form.totalVolume >
            this.form.vehicleMode.vehicleVolume *
            this.form.vehicleMode.vehicleCount
          ) {
            this.$confirm("货物超载，是否继续创建订单", {
              title: "提示",
              type: "warning"
            })
              .then(() => {
                this.create();
              })
              .catch((err) => { });
          } else {
            this.create();
          }
        } else {
          this.create();
        }
      }
    },
    async create () {
      /** 收货时间判断 */
      if (!this.form.toTime) {
        return this.$message.error("请选择收货时间");
      }
      /** 货物信息处理 */
      let arr = this.form.goodsList.filter((item) => {
        return item.goodsId;
      });
      let goodsList = JSON.parse(JSON.stringify(arr));

      /** 多式联运处理 */
      // 跟踪方式调整传值(未选择设备号或填写快递单号不传值给报表)
      let trackType = this.form.deviceCode ? this.form.trackType : null;
      let trackNo = trackType === 1
        ? this.form.deviceCode ? `35160808${this.form.deviceCode}` : null
        : this.form.deviceCode;
      let transportsArr = [];
      if (this.form.checkValue === 1 && this.form.flyNo) {
        transportsArr.push({
          route: {
            sequence: "1",
            startPlace: this.form.currentAddress[0].stationName,
            endPlace: this.form.currentAddress[1].stationName,
            transitNo: this.form.flyNo,
            startTime: this.form.flyTime,
          },
          type: 1
        });
        // if (this.form.receiptAddress.wayDistrictCode) {
        transportsArr.push({
          route: {
            ...this.form.receiptAddress,
            sequence: "2",
            deviceCode: this.form.thirdDeviceCode ? `35160808${this.form.thirdDeviceCode}` : trackNo,
          },
          type: 4
        });
        // }
      } else if (this.form.checkValue === 2 && this.form.trainNum) {
        transportsArr.push({
          route: {
            sequence: "1",
            startPlace: this.form.trainForm,
            endPlace: this.form.trainTo,
            transitNo: this.form.trainNum,
            startTime: this.form.trainTime,
          },
          type: 2
        });
        // if (this.form.receiptAddress.wayDistrictCode) {
        transportsArr.push({
          route: {
            ...this.form.receiptAddress,
            sequence: "2",
            deviceCode: this.form.thirdDeviceCode ? `35160808${this.form.thirdDeviceCode}` : trackNo,
          },
          type: 4
        });
        // }
      } else if (this.form.checkValue === 3) {
        transportsArr.push({
          route: {
            ...this.form.secordReceiptAddress,
            sequence: "1",
            deviceCode: `35160808${this.form.secondDeviceCode}`,
          },
          type: 4
        });
        if (this.form.isThirdShow) {
          transportsArr.push({
            route: {
              ...this.form.receiptAddress,
              sequence: "2",
              deviceCode: `35160808${this.form.thirdDeviceCode}`,
            },
            type: 4
          });
        }
      }
      this.loading = true;
      this.form.routes = [...transportsArr];
      if (!this.form.insure) this.form.insure = 0;
      // 物品总价值等于0，并且有复制的物品总价值时，物品总价值等于复制的总价值
      if (this.form.totalValue === 0 && this.form.calculateValue) this.form.totalValue = this.form.calculateValue
      this.$emit("loading", true);
      //去除上传附件-图片的预览url
      if (this.form.attachments.length) {
        let attachments = this.form.attachments.map(item => {
          return {
            type: 2,
            name: item.name || item.attachName,
            url: item.url || item.attachUrl
          }
        })
        this.form.attachments = attachments
      }
      /* transportMode 为1是零担业务，transportMode 为2是整车业务 */
      /* 所以为零担业务时 vehicle 参数要清除 */
      if (this.form.transportMode === 2) {
        this.form.vehicle = {
          model: this.form.vehicleMode?.vehicleType || null,
          length: this.form.vehicleMode?.vehicleLength || null,
          weight: this.form.vehicleMode?.vehicleWeight || null,
          volume: this.form.vehicleMode?.vehicleVolume || null,
          quantity: this.form.vehicleMode?.vehicleCount || null
        }
        this.form.pick = 0;
        this.form.deliver = 0;
        if (!this.form.onLoad && !this.form.offLoad) {
          this.form.priceUnit = null;
          this.form.chargeMode = null;
        }
      }
      /***** 订单优化相关字段名转化 *****/
      this.form = {
        ...this.form,
        cargoType: this.form.goodsCategory, // 货物分类
        billingUnit: this.form.priceUnit, //计价单位
        billingMode: this.form.chargeMode, //计费模式
        unload: this.form.offLoad,  // 卸货
        load: this.form.onLoad, //装货
        fromAddress: { // 发货信息
          ...this.form.fromAddress,
          contactMobile: this.form.fromContact.contactMobile,
          contactName: this.form.fromContact.contactName,
          precision: this.form.fromAddress.locationType,
        },
        toAddress: { // 收货信息
          ...this.form.toAddress,
          contactMobile: this.form.toContact.contactMobile,
          contactName: this.form.toContact.contactName,
          precision: this.form.toAddress.locationType,
        },
        differenceValue: this.form.valueAddition,
        differenceVolume: this.form.volumeAddition,
        differenceWeight: this.form.weightAddition,
      }

      /***** 清除不需要的参数 *****/
      // for (let key in this.form) {
      //   let arr = [
      //     "fromContact", "toContact", "fromTimeFlag", "goodsCategory",
      //     "vehicleMode", "chargeMode", "offLoad", "onLoad", "priceUnit",
      //     "currentAddress", "secordReceiptAddress", "secondDeviceCode", "receiptAddress", "thirdDeviceCode", "transports",
      //     "checkValue", "deleteFlag", "isThirdShow", "flyNo", "flyTime", "trainForm", "trainNum", "trainTime", "trainTo",
      //     // "totalList", "totalQuantity", "totalValue", "totalVolume", "totalWeight", "valueAddition", "volumeAddition", "weightAddition"
      //   ];
      //   if (arr.includes(key)) {
      //     Reflect.deleteProperty(this.form, key)
      //   }
      // }
      this.form.sourceId = null; //处理同步的sourceId

      let { data } = this.form.id
        ? await order.updateOrder(this.form.id, this.form)
        : await order.createOrder({
          ...this.form,
          goodsList,
          trackNo,
          deviceCode: trackNo,
          trackType
        }).catch(err => {
          this.loading = false;
          this.$emit("loading", false);
        });
      this.$emit("loading", false);
      this.loading = false;
      this.addTotalList();
      this.visible = true;
      if (this.$route.query.draftId) {
        this.deleteDraft();
      }
      this.succeseTips = this.form.id ? "订单修改成功！" : "订单创建成功！";
      this.completeOrderId = this.form.id ? this.form.id : data.orderId;
      this.storage.write(`${this.userId}createForm`, {});
    },
    // 删除草稿
    async deleteDraft () {
      await order.deleteOrderDraft({ draftId: this.$route.query.draftId });
    },
    // 数组去重
    repeatBatch () {
      const testList = []; // 字符串数组
      const dataIdList = [];
      let tableList = [];
      this.form.goodsList.forEach((res) => {
        if (!res.goodsId) return;
        delete res.isRed;
        dataIdList.push(res.goodsId);
        testList.push(
          JSON.stringify({
            goodsId: res.goodsId,
            batchNo: res.batchNo
          })
        );
      });
      tableList = this.unique(testList);
      const goodsIdArr = []; // 储存批次相同订单id
      tableList.forEach((res) => {
        goodsIdArr.push(this.form.goodsList[res].goodsId);
      });
      let repeatArr = []; // 去重后储存订单id
      repeatArr = [...new Set(goodsIdArr)];
      const indexArr = []; // 下标
      repeatArr.forEach((res) => {
        indexArr.push(dataIdList.indexOf(res));
      });
      if (tableList.length > 0) {
        tableList.forEach((res) => {
          this.$set(this.form.goodsList[res], "isRed", true);
        });
        this.$message.error("请修改批次");
        indexArr.forEach((res) => {
          delete this.form.goodsList[res].isRed;
        });
        return false;
      }
    },
    unique (arr) {
      const strList = [];
      for (var i = 1; i < arr.length; i++) {
        for (var j = 0; j < arr.length; j++) {
          if (
            i !== j &&
            arr[i] === arr[j] &&
            arr[i] !== '{"goodsId":"","batchNo":""}'
          )
            strList.push(j, i);
        }
      }
      return [...new Set(strList)];
    },
    initActive (val) {
      this.$emit("initActive", val);
    },
    resetInfo () {
      this.$refs.ruleForm.resetFields();
      this.form.totalWeight = 0;
      this.form.totalVolume = 0;
      this.form.totalValue = 0;
      this.form.totalQuantity = 0;
      this.form.volumeAddition = 0;
      this.form.weightAddition = 0;
      this.form.valueAddition = 0;
      this.form.goodsList = [
        {
          //物品信息
          batchNo: "",
          value: null,
          remarks: "",
          goodsId: null,
          name: "",
          barcode: "",
          quantity: null,
          spec: "",
          volume: null,
          weight: null,
          singleWeight: 0,
          singleVolume: 0,
          singleValue: 0
        }
      ];
      this.form.totalList = [
        {
          batchNo: "",
          value: 0,
          remarks: "",
          goodsId: 0,
          name: "",
          barcode: "补差",
          quantity: 0,
          spec: "",
          volume: this.volumeAddition,
          weight: this.weightAddition,
          singleWeight: 0,
          singleVolume: 0,
          singleValue: 0
        },
        {
          batchNo: "",
          value: this.totalValue,
          remarks: "",
          goodsId: 0,
          name: "",
          barcode: "合计",
          quantity: this.totalQuantity,
          spec: "",
          volume: this.totalVolume,
          weight: this.totalWeight,
          singleWeight: 0,
          singleVolume: 0,
          singleValue: 0
        }
      ];
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/.create_form {
  position: relative;
}
/deep/ .el-input__inner {
  height: 36px !important;
  line-height: 36px !important;
  font-size: 14px;
}
.repeatInput {
  border: 1px solid var(--prev-color-text-purered);
  border-radius: 3px;
}
/deep/ .el-table .cell.el-tooltip span {
  display: inline-block;
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
}
.cellSty::first-letter {
  color: var(--prev-color-primary) !important;
}
.goods-text {
  position: relative;
  padding: 10px 0;
  // margin-bottom: 40px;
  color: var(--prev-icon-color-orange);
  font-size: 16px;
  .el-button {
    position: absolute;
    top: 0;
    right: 0;
  }
}
.operationSty {
  color: var(--prev-color-primary);
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<style>
